let $;
layui.define(['index', 'form', 'table', 'laypage', 'layedit', 'laydate'], function (exports) {
    $ = layui.$;
    let layer = layui.layer;
    let table = layui.table;
    let form = layui.form;
    let layDate = layui.laydate;
    let laypage = layui.laypage;

    zmnLayUtil.layFormVerify(form);
    let cols = [
        [
            {field: 'itemId', type: 'checkbox', fixed: 'left', width: 50, align: 'center'},
            {field: 'itemId', title: 'itemId号',fixed: 'left', width: 150, align: 'center'},
            {field: 'batchName', title: '批次名称', width: 200, align: 'center'},
            {field: 'itemCode', title: '内部券码', width: 305, align: 'center'},
            {field: 'redeemCode', title: '兑换码', width: 200, align: 'center', templet:row=>{
                    return row.redeemCode ? row.redeemCode : "--" ;
                }},
            {field: 'preferentialValue', title: '面值', width: 100, align: 'center', templet: function (row) {
                    var value = "";
                    if (row.preferentialValue) {
                        if (row.preferentialType && row.preferentialType == 1){
                            value = row.preferentialValue/10 + "折";
                        }
                        if (row.preferentialType && row.preferentialType == 2) {
                            value = (row.preferentialValue/100) + "元";
                        }
                    }
                    return value;
                }},
            {field: 'salePrice', title: '优惠券出售价', width: 100, align: 'center', templet: function (row) {
                    var value = "--";
                    if (row.salePrice) {
                        value = (row.salePrice/100) + "元";
                    }
                    return value;
                }},
            {field: 'status', title: '状态', width: 200, align: 'center', templet: function (row) {
                    var  value = "";
                    if(row.status && row.status == 1){
                        value = "已发放（未激活）";
                    }
                    if(row.status && row.status == 2){
                        value = "未使用（已激活）";
                    }
                    if(row.status && row.status == 3){
                        value = "已使用";
                    }
                    if(row.status && row.status == 4){
                        value = "已失效(作废)";
                    }
                    if(row.status && row.status == 5){
                        value = "已失效(过期失效)";
                    }
                    return value;
                }},
            // {field: 'useUserId', title: '用户id', width: 300, align: 'center', templet:row=>{
            //         return row.useUserId ? row.useUserId : "--" ;
            //     }},
            {field: 'useId', title: '用户id', width: 200, align: 'center', templet:row=>{
                    return row.useId ? row.useId : "--" ;
                }},
             {field: 'fcId', title: '厂商ID', width: 200, align: 'center', templet:row=>{
                     return row.fcId ? row.fcId : "--" ;
                 }},
            {field: 'companyName', title: '厂商名称', width: 200, align: 'center', templet:row=>{
                    return row.companyName ? row.companyName : "--" ;
                }},
            // {field: 'orderId', title: '关联订单信息', width: 200, align: 'center', templet:row=>{
            //         return row.orderId ? row.orderId : "--" ;
            //     }},orderIdString
            {field: 'orderIdString', title: '关联订单信息', width: 200, align: 'center', templet:row=>{
                    return "<a lay-href='"+json.omsURL+"/work/detail.action?orderId="+row.orderIdString+"&workId="+row.orderIdString+"' class='layui-table-link' target='_blank'>"+row.orderIdString+"</a>";
                    //return row.orderIdString ? row.orderIdString : "--" ;
                }},
            {field: 'usefulLifeBegin', title: '有效期', width: 200, align: 'center', templet: function (row) {
                    var usefulLifeBegin = "--";var usefulLifeEnd = "";
                    if (row.usefulLifeBegin){
                        usefulLifeBegin = zmnUtil.createTime(row.usefulLifeBegin);
                    }
                    if (row.usefulLifeEnd) {
                        usefulLifeEnd = "--" + zmnUtil.createTime(row.usefulLifeEnd);
                    }
                    return usefulLifeBegin + usefulLifeEnd;
                }},
            {field: 'createTime', title: '创建时间', width: 200, align: 'center', templet: function (row) {
                var createTime = "";
                if (row.createTime){
                    createTime = zmnUtil.createTime(row.createTime);
                }
                return createTime;
            }},
            {field: 'useTime', title: '使用时间', width: 200, align: 'center', templet: function (row) {
                    var useTime = "";
                    if (row.useTime){
                        useTime = zmnUtil.createTime(row.useTime);
                    }
                    return useTime;
                }},
            {
                field: 'itemCodeThird', title: '外部券码', width: 200, align: 'center' , templet: function (row) {
                    if (row.itemCodeThird==""||row.itemCodeThird==''||row.itemCodeThird==null) {
                        return "--";
                    }
                    return row.itemCodeThird;
                }
            },
            {field: 'webSiteName', title: '第三方信息', width: 200, align: 'center', templet:row=>{
                    return row.webSiteName ? row.webSiteName : "--" ;
                }},
            {field: 'merName', title: '第三方公司', width: 200, align: 'center',templet:function (row) {
                    if(!row.merName){
                        return "--";
                    }
                    return row.merName;
                }},
            {field: 'storeName', title: '第三方店铺', width: 200, align: 'center',templet:function (row) {
                    if(!row.storeName){
                        return "--";
                    }
                    return row.storeName;
                }}
        ]
    ];

    layDate.render({
        elem: '#createAndEndDate',
        range: true
    });

    layDate.render({
        elem: '#useDateString',
        range: true
    });

    form.render();


    // let tableRender = function (data) {
    //     zmnLayUtil.layTableRender(table, cols, "zmn-item-table", data, "/coup/item/loadData.action",{limit:50,page:true});
    // };

    // tableRender({});

    var tableRender = function (data) {
        table.render({
            elem: "#zmn-item-table",
            toolbar: "#zmn-item-table-tool",
            title: "分类列表",
            where: data,
            data: json.items,
            limit: json.pageSize,
            cols: cols,
            page: true,
            height: 'full-120',
            done: function (res) {
                $("div[lay-event='LAYTABLE_EXPORT']").attr('lay-event', 'CUSTOM_EXPORT');
            }
        });
        //分页加载数据，必须在表格初始化后
        laypage.render(zmnPage.laypageOptions(json));
    };
    tableRender({});
    form.on('submit(query-submit)', function (obj) {
        var fields = obj.field;
        if((fields.storeName==""||fields.storeName==null)&&fields.merName!=""){
            layer.msg("第三方公司不为空时，第三方店铺必填");
            return false;
        }
        if(fields.status=="已发放(未激活)，"){
            fields.status=1;
        }if(fields.status=="未使用(已激活)"){
            fields.status=2;
        }if(fields.status=="已使用"){
            fields.status=3;
        }if(fields.status=="已失效"){
            fields.status=4;
        }if(fields.status=="已失效(过期作废)"){
            fields.status=5;
        }
        tableRender(fields);
        // return false;
    });

    form.on('submit(zmn-form-reset)', function (obj) {

        $("#batchName").val("");
        $("#useUserId").val("");
        $("#fcId").val("");
        $("#createAndEndDate").val("");
        $("#useDateString").val("");
        $("#itemCode").val("");
        $("#merName").val("");
        $("#storeName").val("");
        $("#status").val("");
        form.render();
        return false;
    });

    /**
     * 描述: 作废
     **/
    $(document).on('click', '#del ', function () {
        var checkData = table.checkStatus('zmn-item-table').data;
        if (checkData.length < 1){
            layer.msg("请选择需要作废的批次");
            return false;
        }else {
            var itemIds = new Array();
            for (var i = 0;i<checkData.length;i++){
                if (checkData[i].status != 2){
                    layer.msg("仅有未使用状态单券可以作废");
                    return false;
                }
                itemIds.push(checkData[i].itemId);
            }
            layer.confirm('优惠券作废', {
                btn: ['确定'] //按钮
            }, function(){
                $.ajax({
                    type: "POST",
                    url: "/coup/item/invalidCoupItem.action",
                    contentType: "application/json",
                    dataType: "json",
                    data: JSON.stringify({itemIds:itemIds}),
                    success: function (json) {
                        if (json.status == 200) {
                            location.reload(true);
                        }
                        layer.msg(json.message);
                    }
                });
            });
        }
    });

    // 启用/停用
    table.on("toolbar(zmn-item-table)", function (obj) {
        if (obj.event == "CUSTOM_EXPORT"){
            console.info( $("#item_form_list").serialize());

            var name ='单券优惠.xlsx';
            var arr=$("#item_form_list").serializeArray();
            var fields=new Object;
            $.each(arr,function(k,v){
                fields[v.name]=v.value;
            });
            if((fields.storeName==""||fields.storeName==null||fields.storeName==undefined)&&fields.merName!=""&&fields.merName!=undefined){
                layer.msg("第三方公司不为空时，第三方店铺必填");
                return false;
            }
            zmnUtil.download("/coup/item/outputExcel?" + $("#item_form_list").serialize(), name, function () {
                layer.close();
            });
            return;
        }
    });



    //对外暴露的接口
    exports('item_list', {});
});
